<?php

namespace App\Http\Controllers\Servers;

use App\Http\Controllers\Controller;
use App\Http\Requests\AddServerRequest;
use App\Http\Requests\DeleteServerRequest;
use App\Models\ConnectionsTypesModel;
use App\Models\ServerModel;
use App\ViewModels\ConnectionsViewModel;
use App\ViewModels\ServerViewModel;

class ServersController extends Controller
{
    public function page()
    {
        return view('servers.index',
            ['title' => 'Сервера', 'servers' => ServerViewModel::make()->listPage(),
                'links' => [['text' => 'Сервера', 'href' => '#']]]);
    }

    public function add()
    {
        return view('servers.add',
            ['title' => 'Добавить сервер', 'connections' => ConnectionsViewModel::make()->getConnectionsNamesAndProperties()]);
    }

    public function delete(DeleteServerRequest $request)
    {
        ServerModel::where('ip_address', '=', $request->get('ip'))->delete();

        return redirect()->back();
    }

    public function addServer(AddServerRequest $request)
    {
        $server = new ServerModel();
        $server->ip_address = $request->get('ip');
        $server->port = $request->get('port');
        $server->name = $request->get('name');
        $connections = ConnectionsTypesModel::query()
            ->whereIn('connection', $request->get('connections'))
            ->get();
        $server->save();
        //костыль
        $server = ServerModel::find($request->get('ip'));

        foreach ($connections as $connection) {
            $request->get('connections');
            $server->connections()->attach($connection->id);
        }

        return redirect()->route('servers.list');
    }
}
